# -*- coding:UTF-8 -*-
import os
import sys
import json
import requests
import urllib3
urllib3.disable_warnings()


class Image(object):
    def __init__(self, url):
        self.url = url
        self.sum_image = 0

    def get_urls(self, resolution):
        req = requests.get(url=self.url)
        res = json.loads(req.text)

        self.sum_image = len(res)

        list_res = []
        for i in range(self.sum_image):
            dict_res = {
                "serial_number": i + 1,
                "user_name": res[i]["user"]["name"],
                "urls_full": res[i]["urls"][resolution]
            }
            list_res.append(dict_res)

        return list_res

    def save_images(self):
        path_dir = input("请在下方输入下载路径\nDownload Path = ")
        name_dir = "images"
        if "/" not in path_dir:
            name_dir = "/" + name_dir
        if ":" not in path_dir:
            print("请重新运行程序并在下载路径中的盘符后面加上冒号")
            os.system("pause")
            exit()

        os.mkdir(path_dir + name_dir)
        
        resolution = input("请在下方输入图片清晰度(raw、full、regular、small、thumb、small_s3)\nresolution = ")
        while resolution not in ["raw", "full", "regular", "small", "thumb", "small_s3"]:
            resolution = input("输入有误，请重新输入！\nresolution = ")

        cnt_download = 1
        for i in self.get_urls(resolution):
            with open(path_dir + "/images" + "/" + i["user_name"] + ".jpg", "wb+") as f:
                req = requests.get(i["urls_full"])

                for data_bit in req.iter_content(128):
                    f.write(data_bit)

                sys.stdout.write("已下载:%.2f%%" % float(cnt_download*100 / self.sum_image) + '\r')
                sys.stdout.flush()
                cnt_download += 1

        print("\n下载完毕！")
        os.system("pause")


if __name__ == "__main__":
    url_index = "https://unsplash.com/napi/photos"
    bg = Image(url=url_index)

    try:
        bg.save_images()
    except FileExistsError:
        print("images文件夹已存在，请重新运行程序，选择新的下载路径：")
        os.system("pause")
    except Exception:
        raise
